<template>
  <div v-if="authStore.isAuthenticated" class="vinyl-manager">
    <div class="header-section">
      <h2 class="title">黑胶唱片管理</h2>
      <a-button type="primary" size="large" @click="addVinyl">
        <template #icon>
          <PlusOutlined />
        </template>
        添加唱片
      </a-button>
    </div>

    <a-list :data-source="vinyls" bordered class="vinyl-list">
      <template #header>
        <div class="list-header">
          <span>唱片列表 ({{ vinyls.length }})</span>
        </div>
      </template>
      <template #renderItem="{ item }">
        <a-list-item class="vinyl-item">
          <div class="vinyl-info">
            <div class="vinyl-name">{{ item.name }}</div>
            <div class="vinyl-artist">{{ item.artist }}</div>
          </div>
          <div class="actions">
            <a-button type="link" size="small" @click="editVinyl(item)">
              <template #icon>
                <EditOutlined />
              </template>
              编辑
            </a-button>
            <a-popconfirm title="确定要删除该唱片吗？" ok-text="确认" cancel-text="取消" @confirm="deleteVinyl(item.id)">
              <a-button type="link" danger size="small">
                <template #icon>
                  <DeleteOutlined />
                </template>
                删除
              </a-button>
            </a-popconfirm>
          </div>
        </a-list-item>
      </template>
    </a-list>

    <a-modal v-model:visible="addModalVisible" title="添加新唱片" @ok="confirmAddVinyl" @cancel="cancelAddVinyl">
      <a-form :model="newVinyl" layout="vertical">
        <a-form-item label="唱片名称">
          <a-input v-model:value="newVinyl.name" placeholder="请输入唱片名称" />
        </a-form-item>
        <a-form-item label="艺术家">
          <a-input v-model:value="newVinyl.artist" placeholder="请输入艺术家名称" />
        </a-form-item>
        <a-form-item label="封面图片">
          <a-upload v-model:file-list="newVinyl.coverImage" :before-upload="() => false" list-type="picture-card"
            accept="image/*" :max-count="1">
            <div>
              <PlusOutlined />
              <div style="margin-top: 8px">上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="editModalVisible" title="编辑唱片信息" @ok="confirmEditVinyl" @cancel="cancelEditVinyl">
      <a-form :model="currentVinyl" layout="vertical">
        <a-form-item label="唱片名称">
          <a-input v-model:value="currentVinyl.name" placeholder="请输入唱片名称" />
        </a-form-item>
        <a-form-item label="艺术家">
          <a-input v-model:value="currentVinyl.artist" placeholder="请输入艺术家名称" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
  <div v-else-if="!authStore.isAuthenticated" class="no-data">
    <p>您必须登录/注册才可以管理胶片</p>
    <p>将在 {{ countdown }} 秒后跳转到主页...</p>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons-vue';
import { useAuthStore } from '../store/auth';
import { useRoute, useRouter } from "vue-router";
import axios from "../axios";
const route = useRoute();
const router = useRouter();

interface Vinyl {
  id: number;
  name: string;
  artist: string;
  coverImage?: File[]; // 新增封面图片字段
}

const vinyls = ref<Vinyl[]>([
  { id: 1, name: 'Abbey Road', artist: 'The Beatles' },
  { id: 2, name: 'Thriller', artist: 'Michael Jackson' },
]);
const authStore = useAuthStore();
const countdown = ref(5); // 倒计时初始值
const addModalVisible = ref(false);


const newVinyl = ref<Vinyl>({
  id: 0,
  name: '',
  artist: '',
  coverImage: [], // 初始化为空数组
});

const currentVinyl = ref<Vinyl>({
  id: 0,
  name: '',
  artist: '',
  coverImage: [], // 初始化为空数组
});

const uploadImageToBackend = async (file: File): Promise<string | null> => {
  const formData = new FormData();
  formData.append('albumImage', file); // 后端要求的参数名是 "albumImage"

  try {
    const response = await axios.post('/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data', // 设置请求头为 multipart/form-data
      },
    });

    if (response.data.code === 200) {
      // 假设后端返回的成功响应中包含图片路径
      return response.data.data; // 返回图片路径
    } else {
      console.error('图片上传失败:', response.data.message);
      return null;
    }
  } catch (error) {
    console.error('图片上传出错:', error);
    return null;
  }
};

const addVinyl = () => {
  newVinyl.value = { id: 0, name: '', artist: '' };
  addModalVisible.value = true;
};

const confirmAddVinyl = async () => {
  if (newVinyl.value.name && newVinyl.value.artist) {
    let imagePath = null;

    // 如果有封面图片，上传到后端
    if (newVinyl.value.coverImage && newVinyl.value.coverImage.length > 0) {
      const file = newVinyl.value.coverImage[0]; // 获取第一个文件
      imagePath = await uploadImageToBackend(file as File);
    }

    const newId = vinyls.value.length > 0 ? Math.max(...vinyls.value.map(v => v.id)) + 1 : 1;
    vinyls.value.push({
      id: newId,
      name: newVinyl.value.name,
      artist: newVinyl.value.artist,
      coverImage: imagePath ? [imagePath] : [], // 保存图片路径
    });

    message.success('添加成功');
    addModalVisible.value = false;
  } else {
    message.error('请填写完整的唱片信息');
  }
};

const cancelAddVinyl = () => {
  addModalVisible.value = false;
};

const editModalVisible = ref(false);

const editVinyl = (vinyl: Vinyl) => {
  currentVinyl.value = { ...vinyl };
  editModalVisible.value = true;
};

const confirmEditVinyl = async () => {
  let imagePath = null;

  // 如果有封面图片，上传到后端
  if (currentVinyl.value.coverImage && currentVinyl.value.coverImage.length > 0) {
    const file = currentVinyl.value.coverImage[0]; // 获取第一个文件
    imagePath = await uploadImageToBackend(file as File);
  }

  const index = vinyls.value.findIndex((v) => v.id === currentVinyl.value.id);
  if (index !== -1) {
    vinyls.value[index] = {
      ...currentVinyl.value,
      coverImage: imagePath ? [imagePath] : [], // 更新图片路径
    };
    message.success('编辑成功');
  }
  editModalVisible.value = false;
};

const cancelEditVinyl = () => {
  editModalVisible.value = false;
};

const deleteVinyl = (id: number) => {
  vinyls.value = vinyls.value.filter((v) => v.id !== id);
  message.success('删除成功');
};

// 监听未登录状态，启动倒计时
watch(() => authStore.isAuthenticated, (isAuthenticated) => {
  if (!isAuthenticated) {
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(timer);
        router.push({ name: 'Home' });
      }
    }, 1000);
  }
}, { immediate: true }); // 立即执行
</script>

<style scoped>
.vinyl-manager {
  padding: 24px;
  background: #f5f5f5;
  border-radius: 8px;
  max-width: 800px;
  margin: 0 auto;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.no-data {
  text-align: center;
  font-size: 1.2em;
  color: #999;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.list-header {
  font-size: 16px;
  font-weight: 500;
  color: #666;
}

.vinyl-list {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.vinyl-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.vinyl-info {
  flex: 1;
}

.vinyl-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.vinyl-artist {
  font-size: 14px;
  color: #999;
}

.actions {
  display: flex;
  gap: 12px;
}

.actions .ant-btn-link {
  padding: 0;
  height: auto;
  line-height: 1;
}
.ant-upload-select-picture-card {
  width: 100px;
  height: 100px;
  margin: 0 auto;
}
</style>